<!-- eslint-disable vue/valid-v-for -->
<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" :title="pageTitle" />
    </div>
    <n-form
      :model="formValues"
      :rules="rules"
      label-placement="left"
      ref="formRef"
      class="py-4"
      :label-width="80"
    >
      <n-card
        :bordered="false"
        title="基本信息"
        class="proCard"
        size="large"
        :segmented="{ content: true }"
      >
        <n-grid cols="2" responsive="screen">
          <n-grid-item offset="0">
            <n-form-item v-show="!isEdit" label="商品分类" path="goodsClassifyId">
              <n-tree-select
                filterable
                :options="classifyData"
                key-field="id"
                label-field="classifyName"
                v-model:value="formValues.goodsClassifyId"
                :on-load="handleClassifyLoad"
              />
            </n-form-item>
            <n-form-item label="商品品牌" path="goodsBrandId">
              <n-tree-select
                filterable
                :options="brandData"
                key-field="id"
                label-field="brandName"
                v-model:value="formValues.goodsBrandId"
              />
            </n-form-item>
            <n-form-item label="商品名称" path="goodsName">
              <n-input v-model:value="formValues.goodsName" placeholder="请输入商品名称" />
            </n-form-item>
            <n-form-item label="商品编号" path="goodsSn">
              <n-input v-model:value="formValues.goodsSn" placeholder="请输入商品编号" />
            </n-form-item>
            <n-form-item label="新旧程度" path="goodsGrade">
              <n-select v-model:value="formValues.goodsGrade" :options="goodsGradeOptions" />
            </n-form-item>
            <n-form-item label="商品标签" path="goodsTags">
              <n-tag
                class="input-goods-tag"
                v-for="item in formValues.goodsTags"
                closable
                @close="handleClose(item)"
              >
                {{ item }}
              </n-tag>
              <n-input
                v-model:value="goodsTag"
                placeholder="请输入标签，回车添加"
                @keyup.enter="addTag"
              />
            </n-form-item>
            <n-form-item label="商品简介" path="goodsDesc">
              <n-input
                type="textarea"
                v-model:value="formValues.goodsDesc"
                placeholder="请输入商品简介"
              />
            </n-form-item>
            <n-form-item label="商品图片" path="goodsImgs">
              <BasicUpload
                :data="{ scene: 'goods' }"
                name="file"
                :width="100"
                :height="100"
                :maxSize="2"
                :maxNumber="5"
                :max="5"
                :multiple="true"
                v-model:value="uploadList"
                helpText="单个文件不超过2MB，最多只能上传5个文件，第一张为封面"
              />
            </n-form-item>
          </n-grid-item>
        </n-grid>
      </n-card>

      <n-card
        :bordered="false"
        title="销售信息"
        class="mt-2 proCard"
        size="large"
        :segmented="{ content: true }"
      >
        <n-grid cols="2" responsive="screen">
          <n-grid-item offset="0">
            <n-form-item label="销售价格" path="goodsPrice">
              <n-input-number
                :precision="2"
                v-model:value="formValues.goodsPrice"
                placeholder="请输入销售价格"
                :show-button="false"
              >
                <template #prefix> ￥ </template>
              </n-input-number>
            </n-form-item>
            <n-form-item label="货号" path="goodsSkuSn">
              <n-input v-model:value="formValues.goodsSkuSn" placeholder="请输入商品货号" />
            </n-form-item>
          </n-grid-item>
        </n-grid>
      </n-card>
      <n-card
        :bordered="false"
        title="商品详情"
        class="mt-2 proCard"
        size="large"
        :segmented="{ content: true }"
      >
        <n-grid cols="2" responsive="screen">
          <n-grid-item offset="0" span="2">
            <BasicEditor height="600" v-model="formValues.goodsIntro" />
          </n-grid-item>
        </n-grid>
      </n-card>
      <n-card class="mt-2 proCard" hoverable>
        <n-space justify="center" style="">
          <n-button type="primary" size="large" :loading="formBtnLoading" @click="formGoodsSubmit"
            >提交</n-button
          >
          <n-button size="large" @click="resetGoodsFrom">重置</n-button>
        </n-space>
      </n-card>
    </n-form>
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, reactive, ref } from 'vue';
  import { useMessage, NButton, TreeSelectOption } from 'naive-ui';
  import { getGoodsClassifyList } from '@/api/goods/goodsClassify';
  import { getBrandList } from '@/api/goods/brand';
  import { BasicResponseModel, saveGoods, updateGoods, getGoods } from '@/api/goods/goods';
  import { ResultEnum } from '@/enums/httpEnum';
  import BasicEditor from '@/components/Editor/BasicEditor.vue';
  import { useRoute } from 'vue-router';
  const rules = {
    goodsClassifyId: {
      required: true,
      message: '请选择商品分类',
      trigger: 'blur',
      type: 'number',
      validator: (_rule: any, value: number) => {
        if (value === 0) {
          return Promise.reject('请选择商品分类');
        } else {
          return Promise.resolve();
        }
      },
    },
    goodsName: {
      required: true,
      message: '请输入商品名称',
      trigger: 'blur',
    },
    goodsSn: {
      required: true,
      message: '请输入商品编号',
      trigger: 'blur',
    },
    goodsDesc: {
      required: true,
      message: '请输入商品简介',
      trigger: 'blur',
    },
    goodsPrice: {
      required: true,
      message: '请输入销售价格',
      trigger: 'blur',
      type: 'number',
      validator: (_rule: any, value: number) => {
        if (value === 0) {
          return Promise.reject('请输入销售价格');
        } else {
          return Promise.resolve();
        }
      },
    },
    goodsSkuSn: {
      required: true,
      message: '请输入商品货号',
      trigger: 'blur',
    },
  };

  const goodsGradeOptions = [
    {
      label: '全新',
      value: 1,
    },
    {
      label: '近新',
      value: 2,
    },
    {
      label: '卓越',
      value: 3,
    },
    {
      label: '优质',
      value: 4,
    },
    {
      label: '良好',
      value: 5,
    },
    {
      label: '合适',
      value: 6,
    },
  ];

  interface Goods {
    id: number;
    goodsName: string;
    goodsClassifyId: number;
    goodsBrandId: number;
    goodsSn: string;
    goodsDesc: string;
    goodsPrice: number; // 商品销售价
    goodsCostPrice: number; // 商品成本价
    goodsMarketPrice: number; // 商品市场价格
    goodsSkuSn: string; //货号
    goodsStatus: number;
    goodsImgs: string[]; // 商品图片
    goodsIntro: string;
    goodsGrade: number;
    goodsTags: string[];
    createTime: string;
  }
  const formValues: Goods = reactive({
    id: 0,
    goodsName: '',
    goodsClassifyId: 0,
    goodsBrandId: 0,
    goodsSn: '',
    goodsDesc: '',
    goodsPrice: 0.0, // 商品销售价
    goodsCostPrice: 0.0, // 商品成本价
    goodsMarketPrice: 0.0, // 商品市场价格
    goodsSkuSn: '', //货号
    goodsStatus: 0,
    goodsImgs: [], // 商品图片
    goodsIntro: '',
    goodsGrade: 1,
    goodsTags: [],
    createTime: 0,
  });
  const formValuesBak = { ...formValues };
  const uploadList = ref([]);
  const formBtnLoading = ref(false);
  const formRef: any = ref(null);
  const message = useMessage();

  const classifyData = ref([]);
  const brandData = ref([]);
  const route = useRoute();

  const pageTitle = ref('添加商品');

  const isEdit = ref(false);

  // 商品标签input
  const goodsTag = ref('');

  onMounted(async () => {
    // 获取分类
    reloadClassifyTree();
    initBrandData();
    const title = route.params.title?.toString();
    const goodsId = route.params.id;
    pageTitle.value = title === undefined ? '添加商品' : title;
    console.log(goodsId);
    if (goodsId) {
      isEdit.value = true;
      let response: BasicResponseModel<any>;
      response = await getGoods({ id: goodsId });
      const goodsInfo = response.result;
      uploadList.value = goodsInfo.goodsImgs;
      //console.log(uploadList.value);
      Object.assign(formValues, goodsInfo);
      Object.assign(formValuesBak, goodsInfo);
    }
  });

  // 新建/编辑中 异步加载
  async function handleClassifyLoad(option: TreeSelectOption) {
    option.children = await getGoodsClassifyList({ pid: option.id });
  }

  async function initBrandData() {
    brandData.value = await getBrandList();
  }

  function formGoodsSubmit(_e: { preventDefault: () => void }) {
    _e.preventDefault();
    formBtnLoading.value = true;
    formValues.goodsImgs = uploadList.value;
    console.log(formValues);
    formRef.value.validate(async (errors: any) => {
      if (!errors) {
        let response: BasicResponseModel<any>;
        if (formValues.id === 0) {
          response = await saveGoods(formValues);
        } else {
          response = await updateGoods(formValues);
        }
        const { message: msg, code } = response;
        if (code == ResultEnum.SUCCESS) {
          message.success(msg);
        } else {
          message.error(msg);
        }
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  /**
   * 添加标签回车事件
   */
  function addTag() {
    const tag = goodsTag.value;
    if (tag !== '') {
      for (let item of formValues.goodsTags) {
        console.log(item);
        if (item === tag) {
          message.error('标签已存在');
          return;
        }
      }
      formValues.goodsTags.push(tag);
      goodsTag.value = '';
    }
  }

  function handleClose(tag: string) {
    console.log('删除：', tag);
  }

  function resetGoodsFrom() {
    // 清空
    Object.assign(formValues, formValuesBak);
  }

  // 刷新表格内数据
  async function reloadClassifyTree() {
    classifyData.value = await getGoodsClassifyList({ pid: 0 });
  }
</script>

<style lang="less" scoped>
  .input-goods-tag {
    margin-right: 5px;
  }
</style>
